﻿using ESRI.ArcGIS.Carto;
using ESRI.ArcGIS.Controls;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.SystemUI;

namespace Swsk33.SimpleArcEngine.Util
{
	/// <summary>
	/// 点击删除图中绘画的元素类
	/// </summary>
	public class DeleteElement : ICommand, ITool
	{
		/// <summary>
		/// 被操作地图对象
		/// </summary>
		private AxMapControl map;

		public void OnCreate(object Hook)
		{
			map = (AxMapControl)Hook;
		}

		public bool Enabled { get { return true; } }

		public bool Checked { get { return false; } }

		public string Name { get; set; }

		public string Caption { get; set; }

		public string Tooltip { get; set; }

		public string Message { get; set; }

		public string HelpFile { get; set; }

		public int HelpContextID { get; set; }

		public int Bitmap { get; set; }

		public string Category { get; set; }

		public int Cursor { get; set; }

		/// <summary>
		/// 鼠标按下
		/// </summary>
		public void OnMouseDown(int button, int shift, int x, int y)
		{
			// 获取地图图像容器
			IGraphicsContainer container = map.ActiveView.GraphicsContainer;
			// 获取鼠标在地图上点的点
			IGeometry point = map.ToMapPoint(x, y);
			// 以该点新建拓扑处理器
			ITopologicalOperator pointOperator = (ITopologicalOperator)point;
			// 以该点建立一个缓冲区
			IGeometry selectBuffer = pointOperator.Buffer(2);
			// 建立缓冲区元素关系对象操作器
			IRelationalOperator bufferOperator = (IRelationalOperator)selectBuffer;
			// 获取当前视图中全部元素
			IEnumElement enumElement = container.LocateElementsByEnvelope(map.Extent);
			// 遍历每一个图中现有的元素
			IElement getElement;
			while ((getElement = enumElement.Next()) != null)
			{
				// 先获取遍历的元素类型
				var elementType = getElement.Geometry.GeometryType;
				switch (elementType)
				{
					// 点类型，则判断是否包含于缓冲图形
					case esriGeometryType.esriGeometryPoint:
						if (bufferOperator.Contains(getElement.Geometry))
						{
							container.DeleteElement(getElement);
						}
						break;
					// 线类型，则判断是否和缓冲图形相交或者线段是否被包含于缓冲图形
					case esriGeometryType.esriGeometryPolyline:
						if (bufferOperator.Crosses(getElement.Geometry) || bufferOperator.Contains(getElement.Geometry))
						{
							container.DeleteElement(getElement);
						}
						break;
					// 面类型，则判断是否和缓冲图形叠置、或者是否互相包含
					case esriGeometryType.esriGeometryPolygon:
						// 创建多边形关系操作对象
						IRelationalOperator polygonOperator = (IRelationalOperator)getElement.Geometry;
						if (bufferOperator.Overlaps(getElement.Geometry) || polygonOperator.Contains(point))
						{
							container.DeleteElement(getElement);
						}
						break;
					default:
						break;
				}
				map.Refresh();
			}
		}

		public void OnClick() { }

		public void OnMouseMove(int button, int shift, int x, int y) { }

		public void OnMouseUp(int button, int shift, int x, int y) { }

		public void OnDblClick() { }

		public void OnKeyDown(int keyCode, int shift) { }

		public void OnKeyUp(int keyCode, int shift) { }

		public void Refresh(int hdc) { }

		public bool OnContextMenu(int x, int y)
		{
			return true;
		}

		public bool Deactivate()
		{
			return true;
		}
	}
}